//
//  WBRefreshControl.swift
//  Weibo8023
//
//  Created by styshy on 15/12/15.
//  Copyright © 2015年 sz. All rights reserved.
//

import UIKit

private let refreshControlOffset:CGFloat = -60

class WBRefreshControl: UIRefreshControl {
    
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopAnimation()
    }
    
    override func beginRefreshing() {
        super.beginRefreshing()
        refreshView.stopAnimation()
    }
    
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0 {
            return
        }
        
        // 判断是否正在刷新
        if refreshing {
            refreshView.startAnimation()
            return
        }
        
        if frame.origin.y < refreshControlOffset && !refreshView.rotateFlag {
            print("反过来")
            refreshView.rotateFlag = true
        } else if frame.origin.y >= refreshControlOffset && refreshView.rotateFlag {
            print("转过去")
            refreshView.rotateFlag = false
        }

    }
    
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        tintColor = UIColor.clearColor()
        
        // 添加刷新视图
        addSubview(refreshView)
        
        // 设置自动布局
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            make.size.equalTo(refreshView.bounds.size)
        }
        
        // 设置监听
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    
    // 是用KVO监听，需要释放
    deinit{
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    private lazy var refreshView:WBRefreshView = WBRefreshView.refreshView()

}

class WBRefreshView:UIView {
    // 旋转标记
    var rotateFlag = false{
        didSet{
            rotateTipIcon()
        }
    }
    
    @IBOutlet weak var loadingIconView: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var tipIconView: UIImageView!
    
    /// 从 XIB 加载 视图
    class func refreshView() -> WBRefreshView {
        
        // 推荐使用 UINib 的方法是加载 XIB
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        
        return nib.instantiateWithOwner(nil, options: nil)[0] as! WBRefreshView
    }
    
    private func rotateTipIcon(){
        var angle = CGFloat(M_PI)
        angle += rotateFlag ? -0.000001 : 0.000001
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIconView.transform = CGAffineTransformRotate(self.transform, CGFloat(angle))
        }
    }
    
    // 播放加载动画
    private func startAnimation(){
        tipView.hidden = true
        
        // 判断动画是否已经被添加
        let key = "transform.rotation"
        if loadingIconView.layer.animationForKey(key) != nil{
            return
        }
        
        print("加载动画播放")
        
        let anim = CABasicAnimation(keyPath: key)
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        anim.removedOnCompletion = false
        
        loadingIconView.layer.addAnimation(anim, forKey: key)
    }
    
    // 停止动画
    private func stopAnimation(){
        tipView.hidden = false
        loadingIconView.layer.removeAllAnimations()
    }
}
